<?php

namespace common\validators;

use Yii;
use common\helpers\FileHelper;
use yii\helpers\StringHelper;
use yii\web\UploadedFile;

/**
 * FileValidator verifies if an attribute is receiving a valid uploaded file.
 *
 * Note that you should enable `fileinfo` PHP extension.
 *
 * @property-read int $sizeLimit The size limit for uploaded files. This property is read-only.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class FileValidator extends \yii\validators\FileValidator {

    /**
     * Checks if given uploaded file have correct type (extension) according current validator settings.
     * @param UploadedFile $file
     * @return bool
     */
    protected function validateExtension($file) {
        $extension = mb_strtolower($file->extension, 'UTF-8');
        if ($this->checkExtensionByMimeType) {
            $mimeType = FileHelper::getMimeType($file->tempName, null, false);
            if ($mimeType === null) {
                return false;
            }
            $officeMimeType = FileHelper::getOfficeMineType($mimeType, $file, $extension);
            $extensionsByMimeType = FileHelper::getExtensionsByMimeType($officeMimeType);
            if (!in_array($extension, $extensionsByMimeType, true)) {
                return false;
            }
        }
        if (!empty($this->extensions)) {
            foreach ((array) $this->extensions as $ext) {
                if ($extension === $ext || StringHelper::endsWith($file->name, ".$ext", false)) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    /**
     * Get MIME type by file path
     *
     * @param string $filePath
     * @return string
     * @throws \yii\base\InvalidConfigException
     * @since 2.0.26
     */
    protected function getMimeTypeByFile($filePath) {
        return FileHelper::getMimeType($filePath);
    }

}
